﻿using System;
using System.Collections.Generic;
using System.Text;
using Autofac;
using IceDog.DNC.Program.Autofac.Helpers;
using IceDog.DNC.Program.Autofac.Model;
using IceDog.DNC.Program.Autofac.Repository;
using IceDog.DNC.Program.Autofac.Services;

namespace IceDog.DNC.Program.Autofac
{
    public class StartUp
    {
        private IContainer _container;
        public StartUp(IContainer container)
        {
            _container = container;
        }
        public void Run()
        {
            WriteDate();
            TestMethod();
        }

        private void TestMethod()
        {
            var helper = _container.Resolve<StringHelper>();
            var book1 = _container.Resolve<Book>();
            var book2 = _container.Resolve<Book>();
            Console.WriteLine("book1==book2:" + (book1 == book2));
        }

        private void WriteDate()
        {
            //常规调用
            //IOutputService output = new ConsoleOutputService();
            //IDateWriterService dateWriter = new TodayWriterService(output);
            //dateWriter.WriteDate();

            // 创建作用域，解析IDateWriter，使用，然后释放
            using (var scope = _container.BeginLifetimeScope())
            {
                var writer = scope.Resolve<IDateWriterService>();
                writer.WriteDate();
            }
            //WriteDate方法要求Autofac提供IDateWriterService.
            //Autofac发现IDateWriterService映射到TodayWriterService所以创建了一个TodayWriterService对象
            //Autofac发现TodayWriterService构造函数需要IOutputService
            //Autofac发现IOutputService映射到ConsoleOutputService，所以创建一个新的ConsoleOutputService的实例
            //Autofac使用ConsoleOutputService实例完成TodayWriterService的创建
            //Autofac返回一个完整的TodayWriterService对象给”WriteDate”来消费
        }
    }
}
